package events

var pools *EventPool
var eventListener map[EventName]*EventListener

func StartEvents(cap int) {
	eventListener = make(map[EventName]*EventListener, 0)
	pools = newEventPool(cap)
	//启动协程池p
	pools.Run()
}

func PublishEvent(event *Event) {
	pools.EntryChannel <- event
}

func StopEvents() {
	if pools != nil {
		pools.Stop()
	}
}

// NewEvent 创建一个新事件
func NewEvent(name EventName, value interface{}) *Event {
	t := Event{
		Name:  name,
		Value: value,
	}
	return &t
}

// RegisterEventListener 注册一个事件监听器
func RegisterEventListener(name EventName, f func(workId int, value interface{})) *EventListener {
	t := &EventListener{
		name: name,
		f:    f,
	}
	eventListener[name] = t
	return t
}

// newEventPool 创建一个协程池
func newEventPool(cap int) *EventPool {
	p := EventPool{
		EntryChannel: make(chan *Event),
		workerNum:    cap,
		JobsChannel:  make(chan *Event),
	}
	return &p
}
